/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatspace.managedBeans;

import chatspace.dao.Dao;
import chatspace.entities.Discussion;
import chatspace.entities.User;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.persistence.NoResultException;
import org.apache.log4j.Logger;
import org.primefaces.event.TabChangeEvent;

/**
 *
 * @author lhoussin
 */
public class ChatMB {

    User connectedUser = new User();
    User advUser;
    String message;
    boolean connectionEstablished = false;
    Dao dao;
    private Logger logger = Logger.getLogger(ChatMB.class.getName());
    List<Discussion> discussions;
    List<User> users;

    /**
     * Creates a new instance of chatMB
     */
    public ChatMB() {
        logger.info("Début du traitement! !");
        try {
            dao = new Dao();
        } catch (Exception ex) {
        }
        users = new ArrayList<User>();
        discussions = new ArrayList<Discussion>();
        //users = dao.findAll("User");
    }

    public User getConnectedUser() {
        return connectedUser;
    }

    public void setConnectedUser(User connectedUser) {
        this.connectedUser = connectedUser;
    }

    public User getAdvUser() {
        return advUser;
    }

    public void setAdvUser(User advUser) {
        //logger.info("AdvUser setted by changing tab advuser.id = " + advUser.getId());
        this.advUser = advUser;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String startChating(List<User> users) {
        users.remove(connectedUser);
        this.users.addAll(users);
        return "GO";
    }

    public void send() {
        logger.info("Conn user = " + connectedUser);
        logger.info("Adv User = " + advUser);
        Discussion d = new Discussion();
        d.setDt(Calendar.getInstance().getTime());
        d.setGroupe(null);
        d.setId(null);
        d.setMessage(message);
        d.setToUser(advUser);
        d.setUser(connectedUser);
        logger.info("Disc.Msg = " + d.getMessage());
        try {
            dao.begin();
            dao.create(d);
            dao.commit();
            discussions.add(d);
        } catch (Exception e) {
            logger.info("Exception :", e);
        }
        message = "";
    }

    public String login() {
        try {
            connectedUser = dao.findUserByLoginAndPassword(connectedUser.getLogin(), connectedUser.getPassword());
        } catch (NoResultException nresex) {
            connectedUser = null;
        }
        logger.info(connectedUser);
        if (connectedUser != null) {
            if (users.size() > 2) {
                users.remove(connectedUser);
                // On verra qui sera le premier advUser
                advUser = users.get(0);
            }
            return "YES";
        } else {
            return "NO";
        }
    }

    public List<User> getUsers() {
        ArrayList first10Users = new ArrayList();
        for (int i = 0; i < ((users.size() >= 10) ? 10 : users.size()); i++) {
            first10Users.add(users.get(i));
        }
        return first10Users;
    }

    public List<User> getOtherUsers() {
        ArrayList otherUsers = new ArrayList();
        for (int i = 10; i < ((users.size() >= 10) ? users.size() : 9); i++) {
            otherUsers.add(users.get(i));
        }
        return otherUsers;
    }

    public void change(TabChangeEvent event) {
        logger.info("changing tab to user");
        advUser = (User) event.getData();
        logger.info(advUser);
        if (connectedUser == null || advUser == null) {
            logger.info("connectedUser ou advUser NULL");
            logger.info("ADVUSER = " + advUser);
            logger.info("ConUSER = " + connectedUser);
            discussions = new ArrayList<Discussion>();
        }

        discussions = dao.findDiscussionByUsers(connectedUser, advUser, 0, 10);
        logger.info("discussionssss are : " + discussions);

    }

    public boolean isConnectionEstablished() {
        return connectionEstablished;
    }

    public void setConnectionEstablished(boolean connectionEstablished) {
        this.connectionEstablished = connectionEstablished;
    }

    public List<Discussion> getDiscussions() {
        discussions = dao.findDiscussionByUsers(connectedUser, advUser, 0, 30);
        java.util.Collections.reverse(discussions);
        for (int i = 1; i < discussions.size(); i++) {
            Discussion discussion = discussions.get(i);
            if (discussions.get(i - 1).getUser().getId() == discussion.getUser().getId()) {
                discussions.get(i - 1).setMessage(discussions.get(i - 1).getMessage() + "\n" + discussion.getMessage());
                if (discussions.remove(discussion)) {
                    i--;
                }
            }
            System.out.println("message = " + discussions.get(i).getMessage());
        }

        logger.info("discussions are : " + discussions);
        return discussions;
    }

//    public Boolean userChanged(Discussion disc) {
//        Boolean b;
//        int index = discussions.indexOf(disc);
//        logger.info("index = " + index);
//        if (index > 0) {
//            if (discussions.get(index - 1).getUser().getId() == discussions.get(index).getUser().getId()) {
//                b = false;
//            } else {
//                b = true;
//            }
//        } else {
//            b = true;
//        }
//        logger.info("HEEEERE Getting value of userchanged = " + b);
//        return true;
//    }
    public void setDiscussions(List<Discussion> discussions) {
        this.discussions = discussions;
    }
}